package day01;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/2/26 17:04
 * 动态数组
 */
public class DynamicArray implements Iterable<Integer> {
    // 逻辑容量
    int size = 0;
    // 数组容量
    private int capacity = 8;
    // 存储元素
    private int array[] = {};

    /**
     * 末尾添加元素
     * @param element
     */
    public void addLast(int element) {
        // array[size] = element;
        // size++;
        add(size, element);
    }

    /**
     * 按指定索引插入元素
     * @param index
     * @param element
     */
    public void add(int index, int element) {
        // 已经满了 需要扩容
        checkAndGrow();
        if (index < 0 || index > size) {
            throw new RuntimeException("index是无效位置!");
        }
        System.arraycopy(array, index, array, index + 1, size - index);
        array[index] = element;
        size++;
    }

    private void checkAndGrow() {
        if (size == 0) {
            array = new int[capacity];
        } else if (size == capacity) {
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0, newArray, 0, size);
            array = newArray;
        }
    }

    /**
     * 按指定索引获取元素
     * @param index
     * @return
     */
    public int get(int index) {
        if (index < 0 || index >= size) {
            throw new RuntimeException("index是无效位置!");
        }
        return array[index];
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("[");
        for (int i = 0; i < size; i++) {
            if (i != size - 1) {
                builder.append(array[i] + ", ");
            } else {
                builder.append(array[i]);
            }
        }
        builder.append("]");
        return builder.toString();
    }

    public void foreach(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }

    public IntStream stream() {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }

    /**
     * 删除元素
     * @param index
     * @return
     */
    public int remove(int index) {
        if (index < 0 || index >= size) {
            throw new RuntimeException("index是无效位置!");
        }
        if (index < size - 1) {
            System.arraycopy(array, index + 1, array, index, size - index - 1);
        }
        size--;
        return array[index];
    }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;
            @Override
            public boolean hasNext() {
                return i < size;
            }

            @Override
            public Integer next() {
                return array[i++];
            }
        };
    }
}
